<?php

/**
 * @author 
 * @copyright 2008
 */
$err = new ErrorWizard;
$table_category = $db->pfx."category";
$table_games = $db->pfx."flash_games";
$table_items = $table_games;
/** per_page */
$per_page = 10;if(isset($_REQUEST['per_page']) and intval($_REQUEST['per_page']) > 0){$per_page = intval($_REQUEST['per_page']);}
/** from */
$from = 0;if(isset($_REQUEST['from']) and intval($_REQUEST['from']) > 0){$from = intval($_REQUEST['from']);}
/** lim_from */
$lim_from = $from*$per_page;
/** do */
$do = 'none';if(isset($_REQUEST['do']) and !empty($_REQUEST['do'])){$do = strval($_REQUEST['do']);}
$main_cat = $db->fetch_one("SELECT * FROM $table_category WHERE alias = 'games' AND pid = '0'");
/** cat_id */
$cat_id = 0;
if(isset($_GET['cat_id']))
{
	$cat_id = intval($_GET['cat_id']);
}
/** item_id */
$item_id = 0;
if (isset($_REQUEST['item_id']))
{
	$item_id = intval($_REQUEST['item_id']);
}

if ($do == 'add')
{
	if(isset($_POST['item']))
	{
		$item = $_POST['item'];
		unset($_POST['item']);
	}
	if(isset($item))
	{
		/** START 	Error Check */
		/** Error Flag */
		$error=false;
		/** Error's Array of Message */
		$errors = array();
		// $error->title
		if (empty($item['title']))
		{
			$error = true;$errors[] = 'Не указано название игры';
		}
		// $error->alias
		if (empty($item['alias']))
		{
			$error = true;$errors[] = 'Не указан альяс игры';
		}
		else
		{
			$is_isset_alias = $db->fetch_one("SELECT COUNT(*) FROM $table_items WHERE alias = '".mysql_real_escape_string($item['alias'])."'");
			if(intval($is_isset_alias[0]) > 0)
			{
				$error = true;
				$errors[] = 'Такой альяс уже существует';
			}
		}
		// $error->content
		if (empty($item['content']))
		{
			$error=true;$errors[] = 'Не указано содержание';
		}
		/** Contest Error */
		if(empty($item['cat_id']) or intval($item['cat_id']) == 0)
		{
			$error=true;$errors[] = 'Не выбрана категория';
		}
		/** END 	Error Check */
		/** IF Errors */
		if($error)
		{
			$message = '<p class="error">'.implode('</p><p class="error">',$errors).'</p>';
			$smarty->assign("message",$message);
			$smarty->assign("item",$item);
		}
		/** Else */
		else
		{
			$insert_item = array(
				'category_id' 	=> intval($item['cat_id']),
				'title' 		=> strval($item['title']),
				'alias' 		=> strval($item['alias']),
				'content' 		=> strval($item['content']),
				'file' 			=> 0,
				'image' 		=> 0,
				'status' 		=> intval($item['status']),
				'time' 			=> time()
			);
			$db->insert($table_items, $insert_item, __FILE__, __LINE__);
			$item_id = $db->last_id();
			if(isset($_FILES['file']))
			{
				if($_FILES['file']['name'] != '' and intval($_FILES['file']['error']) == 0 and intval($_FILES['file']['size']) > 0)
				{
					$item_dir = "/".$this->dir."/";
					$name = $item_id;
					$types = array('swf');
					$res = upload_file_ajax($_FILES['file'],$name,$item_dir,$types);
					if($res)
					{
						$update_item_attach['file'] = 1;
						$db->update($table_items,$update_item_attach,"WHERE id = '$item_id'");
					}
				}
				unset($_FILES['file']);
			}
			if(isset($_FILES['image']))
			{
				if($_FILES['image']['name'] != '' and intval($_FILES['image']['error']) == 0 and intval($_FILES['image']['size']) > 0)
				{
					$item_dir = "/".$this->dir."/";
					$name = $item_id;
					$sizes = array(600,300,150);
					$res = upload_image($_FILES['image'],$name,$item_dir,$sizes);
					if($res)
					{
						$update_item_attach['image'] = 1;
						$db->update($table_items,$update_item_attach,"WHERE id = '$item_id'");
					}
				}
				unset($_FILES['image']);
			}
			$_SESSION['message'] = '<p class="success">Объект успешно добавлен</p>';
			header('Location:'.ADMIN_URL.'/'.$this->full_alias.'?cat_id='.intval($item['cat_id']));die();
		}
	}
}
elseif ($do == 'edit')
{
	if(isset($_POST['item']))
	{
		$item = $_POST['item'];
		unset($_POST['item']);
	}
	if(isset($item))
	{
		/** START 	Error Check */
		/** Error Flag */
		$error=false;
		/** Error's Array of Message */
		$errors = array();
		// $error->title
		if (empty($item['title']))
		{
			$error = true;$errors[] = 'Не указано название игры';
		}
		// $error->alias
		if (empty($item['alias']))
		{
			$error = true;$errors[] = 'Не указан альяс игры';
		}
		else
		{
			$is_isset_alias = $db->fetch_one("SELECT COUNT(*) FROM $table_items WHERE alias = '".mysql_real_escape_string($item['alias'])."' AND id <> '".intval($item['id'])."'");
			if(intval($is_isset_alias[0]) > 0)
			{
				$error = true;
				$errors[] = 'Такой альяс уже существует';
			}
		}
		// $error->content
		if (empty($item['content']))
		{
			$error=true;$errors[] = 'Не указано содержание';
		}
		/** Contest Error */
		if(empty($item['cat_id']) or intval($item['cat_id']) == 0)
		{
			$error=true;$errors[] = 'Не выбрана категория';
		}
		/** END 	Error Check */
		/** IF Errors */
		if($error)
		{
			$message = '<p class="error">'.implode('</p><p class="error">',$errors).'</p>';
			$smarty->assign("message",$message);
			$smarty->assign("item",$item);
		}
		/** Else */
		else
		{
			$item_id = intval($item['id']);
			$update_item = array(
				'category_id' 	=> intval($item['cat_id']),
				'title' 		=> strval($item['title']),
				'alias' 		=> strval($item['alias']),
				'content' 		=> strval($item['content']),
				'status' 		=> intval($item['status'])
			);
			$update_clause = "WHERE id='".$item_id."'";
			$db->update($table_items, $update_item,$update_clause, __FILE__, __LINE__);
			$upload_error = false;
			if(isset($_FILES['file']))
			{
				if($_FILES['file']['name'] != '' and intval($_FILES['file']['error']) == 0 and intval($_FILES['file']['size']) > 0)
				{
					$item_dir = "/".$this->dir."/";
					$name = $item_id;
					$types = array('swf');
					$res = upload_file_ajax($_FILES['file'],$name,$item_dir,$types);

					if($res)
					{
						$update_item_attach['file'] = 1;
						$db->update($table_items,$update_item_attach,"WHERE id = '$item_id'");
					}
					else
					{
						$upload_error = true;
						$_SESSION['message'] = '<p class="error">SWF-файл не загружен</p>';
					}
				}
				unset($_FILES['file']);
			}
			if(isset($_FILES['image']))
			{
				if($_FILES['image']['name'] != '' and intval($_FILES['image']['error']) == 0 and intval($_FILES['image']['size']) > 0)
				{
					$item_dir = "/".$this->dir."/";
					$name = $item_id;
					$sizes = array(600,300,150);
					$res = upload_image($_FILES['image'],$name,$item_dir,$sizes);
					if($res)
					{
						$update_item_attach['image'] = 1;
						$db->update($table_items,$update_item_attach,"WHERE id = '$item_id'");
					}
					else
					{
						$upload_error = true;
						$_SESSION['message'] = '<p class="error">Картинка не загружена</p>';
					}
				}
				unset($_FILES['image']);
			}
			if(!$upload_error)
			{
				$_SESSION['message'] = '<p class="success">Объект успешно изменен</p>';
			}
			
			header('Location:'.ADMIN_URL.'/'.$this->full_alias.'?cat_id='.intval($item['cat_id']));die();
		}
	}
}
elseif($do == 'delete' and $item_id != 0)
{
	$db->del($table_items,"WHERE id='".$item_id."'",__FILE__,__LINE__);
}

if($item_id != 0)
{
	$item = $db->fetch_one("SELECT * FROM $table_items WHERE id='$item_id'");
	if($item != 0)
	{
		$sizes = getimagesize(ROOT_DIR.UPLOAD."flash/".$item_id.".swf");
		$item['file_sizes'] = $sizes[3];
		$smarty->assign("item",$item);
		$do = 'edit';
	}
	else $_SESSION['message'] = '<p class="error">Запрошен несуществующий объект</p>';
}
else $do = 'add';
if($cat_id != 0)
{
	$items = $db->fetch_array("SELECT SQL_CALC_FOUND_ROWS * FROM $table_items WHERE category_id = '$cat_id' ORDER BY time DESC LIMIT $lim_from,$per_page");
	$qnty = $db->fetch_one(QUANTITY);
	if(!empty($items))
	{
		$smarty->assign("items", $items);
		per_page_navigation(intval($qnty[0]),$per_page,$from);
	}
	$cat = $db->fetch_one("SELECT * FROM $table_category WHERE id = '$cat_id'");
	$smarty->assign("cat",$cat);
}
else
{
	$items = $db->fetch_array("SELECT SQL_CALC_FOUND_ROWS * FROM $table_items ORDER BY time DESC LIMIT $lim_from,$per_page");
	$qnty = $db->fetch_one(QUANTITY);
	if(!empty($items))
	{
		$smarty->assign("items", $items);
		per_page_navigation(intval($qnty[0]),$per_page,$from);
	}
}

$query = "SELECT id, title FROM $table_category WHERE pid = '".intval($main_cat['id'])."'";
$rows = $db->fetch_array($query);
$smarty->assign("cats", $rows);
// Сообщение пользователю
if(isset($_SESSION['message']) and !empty($_SESSION['message']))
{$smarty->assign("message",strval($_SESSION['message']));unset($_SESSION['message']);}
$smarty->assign("item_id", $item_id);
$smarty->assign("cat_id", $cat_id);
$smarty->assign("do",$do);
$smarty->assign("per_page",$per_page);
$smarty->assign("from",$from);
?>